package com.ctshk.rpc.system.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.IsDeletedCode;
import com.ctshk.common.enums.NumberConstant;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.model.PageResponse;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.Assist;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.MainDataCollectionDetailListDTO;
import com.ctshk.rpc.system.dto.MainDataCollectionTouristTypeDTO;
import com.ctshk.rpc.system.entity.MainDataCollectionDetails;
import com.ctshk.rpc.system.entity.MainDataCollectionTouristType;
import com.ctshk.rpc.system.mapper.MainDataCollectionDetailsMapper;
import com.ctshk.rpc.system.mapper.MainDataCollectionTouristTypeMapper;
import com.ctshk.rpc.system.mapper.MainDataCurrencyMapper;
import com.ctshk.rpc.system.req.MainDataCollectionDetailAddReq;
import com.ctshk.rpc.system.req.MainDataCollectionDetailListReq;
import com.ctshk.rpc.system.req.MainDataCollectionDetailUpdateReq;
import com.ctshk.rpc.system.req.MainDataCollectionDetailUpdateStatusReq;
import com.ctshk.rpc.system.req.MainDataCollectionOneDetailReq;
import com.ctshk.rpc.system.req.MainDataCollectionTouristTypeReq;
import com.ctshk.rpc.system.service.IMainDataCollectionService;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;

/**
 * <p>
 *
 * </p>
 *
 * @author xuhui
 * @since 1/26/2021
 */
@DubboService
public class MainDataCollectionServiceImpl extends ServiceImpl<MainDataCollectionDetailsMapper, MainDataCollectionDetails> implements IMainDataCollectionService {

    @Autowired
    private MainDataCollectionDetailsMapper mainDataCollectionDetailsMapper;
    @Autowired
    private MainDataCollectionTouristTypeMapper mainDataCollectionTouristTypeMapper;
    @Autowired
    private MainDataCurrencyMapper mainDataCurrencyMapper;
    
    @DubboReference
    IMainDataCurrencyService mainDataCurrencyService;

    volatile boolean isMainDataCollectionTouristTypeExisted = false;

    private Integer insertResult = 0;


    @Override
    public PageResponse<MainDataCollectionDetailListDTO> list(MainDataCollectionDetailListReq mainDataCollectionDetailListReq) {
        Page<MainDataCollectionDetails> page = new Page<>(mainDataCollectionDetailListReq.getPageNo(), mainDataCollectionDetailListReq.getPageSize());
        QueryWrapper<MainDataCollectionDetails> wrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(mainDataCollectionDetailListReq.getCollectionTypeName())) {
            wrapper.lambda().eq(MainDataCollectionDetails::getCollectionTypeName, mainDataCollectionDetailListReq.getCollectionTypeName());
        }
        if (mainDataCollectionDetailListReq.getCollectionTypeId() != null){
            wrapper.lambda().eq(MainDataCollectionDetails::getCollectionTypeId, mainDataCollectionDetailListReq.getCollectionTypeId());
        }
        if (StringUtils.isNotBlank(mainDataCollectionDetailListReq.getName())) {
            wrapper.lambda().like(StringUtils.isNotBlank(mainDataCollectionDetailListReq.getName()), MainDataCollectionDetails::getCollectionName, mainDataCollectionDetailListReq.getName());
        }
        wrapper.lambda().eq(null != mainDataCollectionDetailListReq.getStatus(), MainDataCollectionDetails::getStatus, mainDataCollectionDetailListReq.getStatus());
        wrapper.lambda().eq(MainDataCollectionDetails::getIsDeleted, IsDeletedCode.NO.getCode());
        wrapper.lambda().orderByDesc(MainDataCollectionDetails::getGmtModified);
        Page<MainDataCollectionDetails> iPage = baseMapper.selectPage(page, wrapper);
        List<MainDataCollectionDetails> records = iPage.getRecords();
        List<MainDataCollectionDetailListDTO> mainDataCollectionDetailListDTOS = EntityUtil.copyList(records, MainDataCollectionDetailListDTO.class);
        if (CollectionUtils.isEmpty(mainDataCollectionDetailListDTOS)) {
            return new PageResponse<>(new ArrayList<>(), iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
        }
        for (MainDataCollectionDetailListDTO dto : mainDataCollectionDetailListDTOS) {
            QueryWrapper<MainDataCollectionTouristType> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(MainDataCollectionTouristType::getCollectionDetailsId, dto.getId());
            List<MainDataCollectionTouristType> mainDataCollectionTouristTypes = mainDataCollectionTouristTypeMapper.selectList(queryWrapper);
            List<MainDataCollectionTouristTypeDTO> touristTypeDTOS = EntityUtil.copyList(mainDataCollectionTouristTypes, MainDataCollectionTouristTypeDTO.class);
            
            if (Assist.isNotEmpty(touristTypeDTOS)) {
            	for (MainDataCollectionTouristTypeDTO touristTypeDTO : touristTypeDTOS) {
            		if (touristTypeDTO.getCurrencyId() == null)
            			continue;
            		//汇率
            		touristTypeDTO.setExchangeRate(mainDataCurrencyService.getMarketRateById(touristTypeDTO.getCurrencyId()));
				}
            }
            
            dto.setList(touristTypeDTOS);
        }
        return new PageResponse<>(mainDataCollectionDetailListDTOS, iPage.getCurrent() == 1, iPage.getTotal() <= (iPage.getCurrent() * iPage.getSize()), iPage.getTotal(), iPage.getCurrent(), iPage.getSize());
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result add(MainDataCollectionDetailAddReq req, TokenUser tokenUser) {
        LocalDateTime now = LocalDateTime.now();
        long id = IdWorker.getId();
        for(int m =0;m<req.getList().size();m++){
            MainDataCollectionTouristTypeReq typeReq = req.getList().get(m);
            for(int n =0;n<req.getList().size();n++){
                MainDataCollectionTouristTypeReq typeReq1 = req.getList().get(n);
                if(typeReq.equals(typeReq1)){
                    continue;
                }
                if(typeReq1.getAgeBegin() <= typeReq.getAgeBegin() && typeReq1.getAgeEnd() >= typeReq.getAgeBegin()){
                    Result.failed(SystemError.MAINDATA_4025);
                }else if(typeReq1.getAgeBegin() <= typeReq.getAgeEnd() && typeReq1.getAgeEnd() >= typeReq.getAgeEnd()){
                    Result.failed(SystemError.MAINDATA_4025);
                }
            }
        }
        MainDataCollectionDetails details = EntityUtil.copy(req, MainDataCollectionDetails.class);
        details.setId(id);
        details.setIsDeleted(IsDeletedCode.NO.getCode());
        details.setCreateId(tokenUser.getId());
        details.setModifiedId(tokenUser.getId());
        details.setGmtCreate(now);
        details.setGmtModified(now);
        baseMapper.insert(details);
        for (MainDataCollectionTouristTypeReq mainDataCollectionTouristTypeReq:req.getList()) {
            MainDataCollectionTouristType touristType = EntityUtil.copy(mainDataCollectionTouristTypeReq, MainDataCollectionTouristType.class);
            touristType.setId(IdWorker.getId());
            touristType.setIsDeleted(IsDeletedCode.NO.getCode());
            touristType.setCollectionDetailsId(id);
            touristType.setCreateId(tokenUser.getId());
            touristType.setModifiedId(tokenUser.getId());
            touristType.setGmtCreate(now);
            touristType.setGmtModified(now);
            mainDataCollectionTouristTypeMapper.insert(touristType);
        }
        return Result.success(id);
    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result update(MainDataCollectionDetailUpdateReq req, TokenUser tokenUser) {
        LocalDateTime now = LocalDateTime.now();
        for(int m =0;m<req.getList().size();m++){
            MainDataCollectionTouristTypeReq typeReq = req.getList().get(m);
            for(int n =0;n<req.getList().size();n++){
                MainDataCollectionTouristTypeReq typeReq1 = req.getList().get(n);
                if(typeReq.equals(typeReq1)){
                    continue;
                }
                if(typeReq1.getAgeBegin() <= typeReq.getAgeBegin() && typeReq1.getAgeEnd() >= typeReq.getAgeBegin()){
                    Result.failed(SystemError.MAINDATA_4025);
                }else if(typeReq1.getAgeBegin() <= typeReq.getAgeEnd() && typeReq1.getAgeEnd() >= typeReq.getAgeEnd()){
                    Result.failed(SystemError.MAINDATA_4025);
                }
            }
        }
        MainDataCollectionDetails details = EntityUtil.copy(req, MainDataCollectionDetails.class);
        details.setModifiedId(tokenUser.getId());
        details.setGmtModified(now);
        baseMapper.updateById(details);
        QueryWrapper<MainDataCollectionTouristType> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(MainDataCollectionTouristType::getCollectionDetailsId,req.getId());
        mainDataCollectionTouristTypeMapper.delete(wrapper);
        for (MainDataCollectionTouristTypeReq mainDataCollectionTouristTypeReq:req.getList()) {
            MainDataCollectionTouristType touristType = EntityUtil.copy(mainDataCollectionTouristTypeReq, MainDataCollectionTouristType.class);
            touristType.setIsDeleted(IsDeletedCode.NO.getCode());
            touristType.setId(IdWorker.getId());
            touristType.setCollectionDetailsId(req.getId());
            touristType.setCreateId(tokenUser.getId());
            touristType.setModifiedId(tokenUser.getId());
            touristType.setGmtCreate(now);
            touristType.setGmtModified(now);
            mainDataCollectionTouristTypeMapper.insert(touristType);
        }
        return Result.success(req.getId());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<List<MainDataCollectionTouristTypeDTO>> detail(MainDataCollectionOneDetailReq mainDataCollectionDetailReq, TokenUser currentUser) {
        List<MainDataCollectionTouristType> mainDataCollectionTouristTypeList;
        QueryWrapper<MainDataCollectionDetails> detailsQueryMapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(mainDataCollectionDetailReq.getCollectionName())) {
            detailsQueryMapper.eq("collection_name", mainDataCollectionDetailReq.getCollectionName());
        }
        if (StringUtils.isNotBlank(mainDataCollectionDetailReq.getCollectionTypeName())) {
            detailsQueryMapper.eq("collection_type_name", mainDataCollectionDetailReq.getCollectionTypeName());
        }

        MainDataCollectionDetails mainDataCollectionDetails = mainDataCollectionDetailsMapper.selectOne(detailsQueryMapper);
        QueryWrapper<MainDataCollectionTouristType> queryWrapper = new QueryWrapper();
        queryWrapper.eq("collection_details_id", mainDataCollectionDetails.getId());
        System.out.println("mainDataCollectionDetails.getId() = " + mainDataCollectionDetails.getId());
        List<MainDataCollectionTouristTypeDTO> mainDataCollectionTouristTypeDTOList = new ArrayList<>();
        mainDataCollectionTouristTypeList = mainDataCollectionTouristTypeMapper.selectList(queryWrapper);
        mainDataCollectionTouristTypeList.forEach(i -> {
            MainDataCollectionTouristTypeDTO mainDataCollectionTouristTypeDTO = EntityUtil.copy(i, MainDataCollectionTouristTypeDTO.class);
            mainDataCollectionTouristTypeDTOList.add(mainDataCollectionTouristTypeDTO);
        });
        return new Result(mainDataCollectionTouristTypeDTOList);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Integer> delete(Long collectionDetailsId, TokenUser currentUser) {
        List<MainDataCollectionTouristType> mainDataCollectionTouristTypeList = new ArrayList<>();
        MainDataCollectionTouristType mainDataCollectionTouristType = new MainDataCollectionTouristType();
        mainDataCollectionTouristType.setCollectionDetailsId(collectionDetailsId);
        mainDataCollectionTouristType.setIsDeleted(NumberConstant.ONE.getValue());
        MainDataCollectionDetails mainDataCollectionDetails = new MainDataCollectionDetails();
        mainDataCollectionDetails.setIsDeleted(NumberConstant.ONE.getValue());
        UpdateWrapper<MainDataCollectionDetails> collectionDetailsUpdateWrapper = new UpdateWrapper<MainDataCollectionDetails>();
        collectionDetailsUpdateWrapper.eq("id", collectionDetailsId);
        mainDataCollectionDetailsMapper.update(mainDataCollectionDetails, collectionDetailsUpdateWrapper);
        UpdateWrapper<MainDataCollectionTouristType> collectionTouristTypeUpdateWrapper = new UpdateWrapper<>();
        System.out.println("mainDataCollectionTouristType.getId() = " + mainDataCollectionTouristType.getId());
        collectionTouristTypeUpdateWrapper.eq("collection_details_id", mainDataCollectionTouristType.getCollectionDetailsId());
        if (null != currentUser) {
            mainDataCollectionTouristType.setModifiedId(currentUser.getId());
        }
        Integer resultInt = mainDataCollectionTouristTypeMapper.update(mainDataCollectionTouristType, collectionTouristTypeUpdateWrapper);
        mainDataCollectionTouristTypeList.add(mainDataCollectionTouristType);
        return Result.success(resultInt);

    }


    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Integer> modifyStatus(MainDataCollectionDetailUpdateStatusReq mainDataCollectionDetailUpdateStatusReq, TokenUser currentUser) {
        MainDataCollectionDetails mainDataCollectionDetails = new MainDataCollectionDetails();

        mainDataCollectionDetails.setId(mainDataCollectionDetailUpdateStatusReq.getId());
        mainDataCollectionDetails.setStatus(mainDataCollectionDetailUpdateStatusReq.getStatus());
        if (null != currentUser) {
            mainDataCollectionDetails.setModifiedId(currentUser.getId());
        }
        UpdateWrapper<MainDataCollectionDetails> collectionDetailsmodifyStatusWrapper = new UpdateWrapper<MainDataCollectionDetails>();
        collectionDetailsmodifyStatusWrapper.eq("id", mainDataCollectionDetailUpdateStatusReq.getId());
        return new Result(mainDataCollectionDetailsMapper.update(mainDataCollectionDetails, collectionDetailsmodifyStatusWrapper));

    }

}

